package lowijs.XfDroid;

import java.io.*;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;

import android.app.*;
import android.content.*;
import android.os.*;

public class XfDroidService extends Service implements XfireObserver {
	private static final int NM_NONE = 0;
	private static final int NM_ALL = 1;
	private static final int NM_OTHER = 2;
	
	private static int notificationMode = NM_ALL;
	private static Conversation activeConvo = null;
	
	public void onCreate() {
		super.onCreate();
		EventManager.addObserver(this);
		
		// Setup storage
		if(!Environment.getExternalStorageState()
				.equals(Environment.MEDIA_MOUNTED)) {
			Util.STORAGE_PATH = null;
		} else {
			Util.STORAGE_PATH = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/xfdroid";
			File dir = new File(Util.STORAGE_PATH);
			dir.mkdirs();
		}

	}
		
	public void onDestroy() {
		super.onDestroy();
		EventManager.removeObserver(this);
		
		activeConvo = null;
	}
	
	public static void sendAllNotifications() {
		notificationMode = NM_ALL;
		activeConvo = null;
	}
	
	public static void sendNoNotifications() {
		notificationMode = NM_NONE;
		activeConvo = null;
	}
	
	public static void sendNoNotificationsFor(Conversation cv) {
		notificationMode = NM_OTHER;
		activeConvo = cv;
	}

	public void handleEvent(XfireEvent event) {
		switch(event.getEventType()) {
		case XfireEvent.XF_RECVIM:
			ReceiveImEvent e = (ReceiveImEvent)event;
			if (notificationMode == NM_NONE ||
					activeConvo == e.getConversation())
				return;
			
			Friend f = e.getConversation().getFriend();
			Bundle b = new Bundle();
			b.putByteArray("friend", f.getUserid());
			
			int userid = Util.fromBytes(f.getUserid(), 0, 4);
			
			String msgFrom = getString(R.string.message_from);
			postNotification(msgFrom + " " + f.getNick(), f.getNick(),
					e.getIm().getMessage(), b, userid);
			return;
		case XfireEvent.XF_OFFLINE:
			stopSelf();
			return;
		}
	}
	
	private void postNotification(String ticker, String title, String message,
			Bundle extras, int id) {
		NotificationManager nm = (NotificationManager)getSystemService(
				NOTIFICATION_SERVICE);
		
		Notification n = new Notification(R.drawable.xfire_notif, ticker,
				System.currentTimeMillis());
		
		n.flags |= Notification.FLAG_AUTO_CANCEL;
		n.defaults |= Notification.DEFAULT_ALL;
		
		Intent i = new Intent(this, ConvoWindow.class);
		i.putExtras(extras);
		i.setFlags(Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_ACTIVITY_NO_HISTORY
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		
		PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
		
		n.setLatestEventInfo(this, title, message, pi);
		nm.notify(id, n);
	}

	/*
	 * Unused.
	 */
	public IBinder onBind(Intent arg0) {
		return null;
	}
}
